package com.clwl.supervise.superviseapp.controller.inspection;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.config.RepeatSubmit;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.DailySaveVo;
import com.clwl.supervise.superviseapp.entity.pro.JgProCompanyDailyScore;
import com.clwl.supervise.superviseapp.entity.pro.JgTcCompany;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.JgDailyCheck;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.service.company.TcCompanyService;
import com.clwl.supervise.superviseapp.service.inspect.DailyInspectService;
import com.clwl.supervise.superviseapp.service.pro.JgProCompanyDailyScoreService;
import com.clwl.supervise.superviseapp.util.HolidayUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.YearMonth;
import java.util.*;

/**
 * 日常检查
 */
@RestController
@RequestMapping("dailyInspect")
public class DailyInspectController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DailyInspectService dailyInspectService;
    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private TcCompanyService tcCompanyService;

    @Autowired
    private JgProCompanyDailyScoreService jgProCompanyDailyScoreService;

    /**
     * 获取日常检查的企业列表
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    @GetMapping("page")
    public ResultEntity page(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity, String processBathQueryEntity, String processBathQueryId, String processBathQueryCode
    ) {
        if (commonSearchEntity.getProcessId() != null && commonSearchEntity.getProcessId().intValue() == 4) {

            List<String> holidayList = HolidayUtil.getYearHolidays(DateUtil.year(new Date()));
            Page<JgTcCompany> proList = tcCompanyService.selectProList(pageNum, pageSize, commonSearchEntity);
            Calendar cal = Calendar.getInstance();  // 获取当前时间的Calendar实例
            int year = cal.get(Calendar.YEAR);  // 获取年份
            //判断要过期时间
            for (JgTcCompany company : proList.getRecords()) {
                company.setProcessName("食品生产环节");
                QueryWrapper<JgProCompanyDailyScore> r = new QueryWrapper<>();
                r.eq("company_id", company.getId());
                r.eq("year", company.getYear() == null || "".equals(company.getYear()) ? year : company.getYear());
                r.orderByAsc("serial_num");
                List<JgProCompanyDailyScore> dailyScoreList = jgProCompanyDailyScoreService.list(r);
                //判断要过期时间 10天
                for (JgProCompanyDailyScore jgProCompanyDailyScore : dailyScoreList) {
                    //获取过期月份最后一天
                    if( jgProCompanyDailyScore.getCheckExpireMonth() != null && jgProCompanyDailyScore.getCheckExpireMonth() != 0) {
                        int lastDay = YearMonth.of(year, jgProCompanyDailyScore.getCheckExpireMonth()).lengthOfMonth();
                        String expireMonth = year + "-" + jgProCompanyDailyScore.getCheckExpireMonth() + "-" + lastDay;
                        //判断与当前日期相差天数
                        long days = HolidayUtil.getLastYearWorkdayDays(DateUtil.parse(expireMonth), new Date(), holidayList);
                        if (days <= 10) {
                            jgProCompanyDailyScore.setAdventStatus("L");
                        } else {
                            jgProCompanyDailyScore.setAdventStatus("Z");
                        }
                    }
                }
                company.setDailyScoreList(dailyScoreList);
            }
            return ResultEntity.success(proList);
        } else {
            Page<Map<String, Object>> pageList = dailyInspectService.selectCompanyPage(pageNum, pageSize, commonSearchEntity, processBathQueryEntity, processBathQueryId, processBathQueryCode);
            return ResultEntity.success(pageList);
        }

    }


    /**
     * 日常检查的检查结果列表
     *
     * @param pageNum  当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    @GetMapping("inspectionResultPage")
    public ResultEntity<List<Map<String, Object>>> inspectionResultPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        IPage<Map<String, Object>> pageList = dailyInspectService.selectInspectionResultPage(pageNum, pageSize, commonSearchEntity);
        return ResultEntity.success(pageList.getRecords());
    }


    /**
     * 获取检查的时候基础信息
     *
     * @param checkId   检查id 如果之前临时保存过
     * @param companyId 企业id
     * @param checkNum  第几次检查 如果传递的是null则获取最新的见擦汗次数加一来生成检查单
     * @return
     */
    @GetMapping("getInspectionBaseInfo")
    @RepeatSubmit
    public ResultEntity<Map<String, Object>> getInspectionBaseInfo(Long checkId, Long companyId, Integer checkNum) {
        try {
            if (companyId == null) {
                return ResultEntity.error("请传递企业id");
            }
//            Map<String, Object> superviseInfo = dailyInspectService.selectSuperviseInfo(checkId, companyId, checkNum);
            Map<String, Object> checkInfo = dailyInspectService.selectCheckInfo(checkId, companyId, checkNum);
            List<Map<String, Object>> dictList = dailyInspectService.getDictList();
            JgPointDistance distance = baseDataService.getCheckDistance(companyId + "");
            checkInfo.put("DISTANCE", distance.getDistance());
            Map<String, Object> result = new HashMap<>();
            result.put("abnormalReasonType", dictList);
            //是否显示社会责任评分：1:是，0：否
            String liability = dailyInspectService.getLiability(companyId,checkId);
            result.put("IS_LIABILITY", "0");
            result.putAll(checkInfo);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 获取日常检查的检查项目列表
     *
     * @param checkId   检查iD
     * @param companyId 企业Id
     * @return
     */
    @GetMapping("checkItemList")
    public ResultEntity<Map<String, Object>> checkItemList(Long checkId, Long companyId) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> itemList = dailyInspectService.selectCheckItemList(checkId, companyId);
            result.put("templateName", itemList.size() > 0 ? itemList.get(0).get("TEMPLATE_NAME") : "");
            result.put("itemList", itemList);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 社会责任评分模版列表  社会责任评分标准表：jg_liability_standard，社会责任评分内容：jg_liability_content
     *
     * @param checkId
     * @param companyId
     * @return
     */
    @GetMapping("liabilityItemList")
    public ResultEntity<Map<String, Object>> liabilityItemList(Long checkId,Long dynamicScoringId, Long companyId) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<Map<String, Object>> mapList = dailyInspectService.selectLiabilityItem(checkId,dynamicScoringId, companyId);
            result.put("templateName", !mapList.isEmpty() ? mapList.get(0).get("TEMPLATE_NAME") : "");
            result.put("itemList", mapList);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 保存检查项结果内容
     *
     * @param checkId                 检查Id
     * @param templateId              模板id
     * @param standardId              检查标准id
     * @param contentId               检查内容Id
     * @param result                  选择的结果 1是、2否、3合理缺项
     * @param problemContent          问题描述选择的内容
     * @param checkExplain            检查说明选择的内容
     * @param problemContentInput     问题描述输入的内容
     * @param missingItemContentInput 检查说明输入的内容
     * @param taskIds                 关联合并任务的id
     * @return
     * @deprecated 页面不实时保存
     */
    @PostMapping("saveCheckItem")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckItem(Long checkId, Long templateId, Long standardId, Long contentId, String result,
                                      String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput, String taskIds
    ) {
        try {
            dailyInspectService.saveCheckItem(checkId, standardId, contentId, result,
                    problemContent, checkExplain, problemContentInput, missingItemContentInput);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},checkNum:{},templateId:{},standardId:{}, contentId:{}, result:{},   problemContent:{}, checkExplain:{}",
                    checkId, templateId, standardId, contentId, result, problemContent, checkExplain);
            return ResultEntity.error("上传失败");
        }
    }


    @PostMapping("saveLiability")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveLiability(Long checkId, Long templateId, Long standardId, Long contentId, String result,
                                      String problemContent, String checkExplain, String problemContentInput, String missingItemContentInput, String taskIds
    ) {
        try {
            dailyInspectService.saveLiability(checkId, standardId, contentId, result,
                    problemContent, checkExplain, problemContentInput, missingItemContentInput);
            return ResultEntity.success();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},checkNum:{},templateId:{},standardId:{}, contentId:{}, result:{},   problemContent:{}, checkExplain:{}",
                    checkId, templateId, standardId, contentId, result, problemContent, checkExplain);
            return ResultEntity.error("上传失败");
        }
    }


    /**
     * 保存检查门头照照片
     *
     * @param checkId 检查Id
     * @param file    门头照文件
     * @return
     */
    @PostMapping("uploadCheckFile")
    public ResultEntity uploadCheckFile(Long checkId, MultipartFile file) {
        try {
            JgDailyCheck check = dailyInspectService.uploadCheckFile(checkId, file);
            return ResultEntity.success(check);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 上传检查项的问题照片
     *
     * @param checkId    检查id
     * @param standardId 检查标准id
     * @param contentId  检查内容Id
     * @param file
     * @return
     * @deprecated 页面不实时上传了
     */
    @PostMapping("uploadItemFile")
    public ResultEntity uploadItemFile(Long checkId, Long standardId, Long contentId, MultipartFile file
    ) {
        try {
            String fileUrl = dailyInspectService.uploadItemFile(checkId, standardId, contentId, file);
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置当前的检查内容失败checkId:{},standardId:{}, contentId:{}",
                    checkId, standardId, contentId);
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 保存/临时保存检查项结果内容
     *
     * @return
     */
    @PostMapping("saveCheckInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity saveCheckInfo(DailySaveVo dailySaveVo) {
        try {
            JgDailyCheck dailyCheck = dailyInspectService.saveCheckInfo(dailySaveVo, false);
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 最终保存
     * @return
     */
    @PostMapping("finaSaveInfo")
    @RepeatSubmit(lockTime = 10)
    public ResultEntity finaSaveInfo(DailySaveVo dailySaveVo) {
        try {
            JgDailyCheck dailyCheck = dailyInspectService.finaSaveInfo(dailySaveVo, false);
            return ResultEntity.success(dailyCheck);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("保存/临时保存检查项结果内容失败");
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 上传结果记录的文件
     *
     * @param checkId 日常检查结果表id
     * @param imgFile 二进制文件流
     * @param type    1-要点表；2-记录表
     * @return
     */
    @PostMapping("uploadResultRecord")
    public ResultEntity uploadResultRecord(Long checkId, @RequestPart(required = true, name = "imgFile") MultipartFile imgFile, String type
    ) {
        try {
            if (imgFile != null && StringUtils.isBlank(imgFile.getOriginalFilename())) {
                return ResultEntity.error("请上传文件");
            }
            String fileUrl = dailyInspectService.uploadResultRecord(checkId, imgFile, type);
            return ResultEntity.success(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传结果记录的文件失败");
            return ResultEntity.error("操作失败");
        }
    }


    /**
     * 查询检查完成的订单
     *
     * @param checkId 日常检查表id
     * @return
     */
    @GetMapping("getCheckResultInfo")
    public ResultEntity getCheckResultInfo(Long checkId) {
        try {
            Map<String, Object> result = dailyInspectService.getCheckResultInfo(checkId);
            return ResultEntity.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查完成的订单失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询检查内容的列表
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    @GetMapping("getCheckInfo")
    public ResultEntity getCheckInfo(Long checkId) {
        try {
            JgDailyCheck checkInfo = dailyInspectService.getCheckInfo(checkId);
            return ResultEntity.success(checkInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查信息失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询结果表需要的数据
     *
     * @param checkId 日常检查表JG_DAILY_CHECK  id
     * @return
     */
    @GetMapping("getResultTable")
    public ResultEntity getResultTable(Long checkId) {
        try {
            Map<String, Object> resultTable = dailyInspectService.getResultTable(checkId);
            return ResultEntity.success(resultTable);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查信息失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 查询检查内容的列表
     *
     * @param dailyStandardId 日常检查表id
     * @return
     */
    @GetMapping("getCheckContentList")
    public ResultEntity getCheckContentList(Long dailyStandardId) {
        try {
            List<Map<String, Object>> contentList = dailyInspectService.getCheckContentList(dailyStandardId);
            return ResultEntity.success(contentList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error("操作失败");
        }
    }

    /**
     * 保存告知单
     *
     * @param checkAddress         检查地址
     * @param checkPerson1Id       第一检查人id
     * @param checkPerson1SignFile 第一检查人签名文件流
     * @param checkPerson2Id       第二检查人id
     * @param checkPerson2SignFile 第二检查人签名文件流
     * @param checkId              检查ID
     * @param companySignFile      企业签名文件流
     * @param informFile           电子告知单文件流
     * @param isAvoid              是否回避0-否；1-是
     * @param notifyMatters
     * @param taskIds              合并关联任务的id
     * @return
     */
    @PostMapping("saveCheckInform")
    public ResultEntity saveCheckInform(Long checkId, Long checkPerson1Id, Long checkPerson2Id,
                                        String checkAddress, String notifyMatters, String isAvoid, String companySignFile
            , String checkPerson1SignFile
            , String checkPerson2SignFile
            , String informFile, String taskIds
    ) {
        try {
            String urlPath = dailyInspectService.saveCheckInform(checkId, checkPerson1Id, checkPerson2Id,
                    checkAddress, notifyMatters, isAvoid, companySignFile, checkPerson1SignFile, checkPerson2SignFile, informFile, taskIds);
            return ResultEntity.success(urlPath);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error(e.getMessage());
        }
    }

    /**
     * 获取待办的专项检查任务
     *
     * @return
     */
    @GetMapping("getSpecialInspectList")
    public ResultEntity getSpecialInspectList(Long companyId) {
        try {
            List<Map<String, Object>> taskList = dailyInspectService.getSpecialInspectList(companyId);
            return ResultEntity.success(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询检查内容的列表失败");
            return ResultEntity.error("操作失败");
        }
    }

}
